package com.sprouting.personal.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.sprouting.personal.annotations.ApiIdempotent;
import com.sprouting.personal.interfaces.common.Constant;
import com.sprouting.personal.model.common.ResultJson;
import com.sprouting.personal.model.common.jsr.AddGroup;
import com.sprouting.personal.model.common.jsr.UpdGroup;
import com.sprouting.personal.model.entity.Dict;
import com.sprouting.personal.model.entity.Website;
import com.sprouting.personal.service.DictService;
import com.sprouting.personal.service.WebsiteService;
import com.sprouting.personal.utils.CheckTool;
import com.sprouting.personal.utils.EntityTool;
import com.sprouting.personal.utils.IdTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 网址
 *
 * @author ：LX（长沙麓谷）
 * @date 创建时间： 2022/9/11 0:48
 */
@RequestMapping("/web")
@RestController
@Slf4j
public class WebsiteController {

    @Autowired
    private WebsiteService websiteService;
    @Autowired
    private DictService dictService;


    // 解决查看的时候是错误的问题，保存后变了

    /**
     * 检查是否连接通过
     * @param id 网址ID
     * @return
     */
    @PostMapping("/checkConnection")
    public ResultJson checkConnection(String id){
        if (CheckTool.checkNull(id)){
            return ResultJson.errorIllegal();
        }
        Website website = websiteService.getWebsiteById(id);
        if (website == null){
            return ResultJson.errorPram();
        }

        if (Constant.YesOrNo.YES.equals(website.getOverTheWall())){
            return ResultJson.success(4);
        }

        try {
            HttpResponse execute = HttpRequest.get(website.getUrl()).timeout(20000).execute();
            int status = execute.getStatus();
            if (status == 200){
                return ResultJson.success(2);
            }
        } catch (Exception e) {
            return ResultJson.success(3);
        }

        return ResultJson.success(3);
    }

    /**
     * 网址新增了一次点击事件
     * @param id 网址ID
     * @return
     */
    @PostMapping("/addOneClick")
    public ResultJson addOneClick(String id){
        if (CheckTool.checkNull(id)){
            return ResultJson.errorIllegal();
        }
        Website website = websiteService.getWebsiteById(id);
        if (website == null){
            return ResultJson.errorPram();
        }
        Integer numberOfClicks = website.getNumberOfClicks();
        if (numberOfClicks == null){
            website.setNumberOfClicks(1);
        } else {
            website.setNumberOfClicks(website.getNumberOfClicks() + 1);
        }

        websiteService.updateById(website);
        return ResultJson.success(website);
    }

    /**
     * 查询全部网址信息
     * @param website 网址信息
     * @param sort 排序字段
     * @return
     */
    @PostMapping("/getWebList")
    public ResultJson getWebList(Website website, String sort){
        if (website == null){
            website = new Website();
        }
        website.setUserId(StpUtil.getLoginIdAsString());
        return ResultJson.success(websiteService.getWebList(website, sort));
    }

    /**
     * 物理删除网址信息
     * @param id 网址ID
     * @return
     */
    @PostMapping("/delWebsiteById")
    public ResultJson delWebsiteById(String id){
        if (CheckTool.checkNull(id)){
            return ResultJson.errorIllegal();
        }

        websiteService.removeById(id);
        return ResultJson.success(null);
    }

    /**
     * 更新网址信息
     * @param website 网址信息
     * @return
     */
    @PostMapping("/updWebsite")
    @ApiIdempotent
    public ResultJson updWebsite(@Validated(UpdGroup.class) Website website){
        String msg = checkWebsite(website);
        if (msg != null){
            return ResultJson.error(msg);
        }

        EntityTool.buildUpdBase(website, StpUtil.getLoginIdAsString());
        websiteService.updateById(website);
        return ResultJson.success(website);
    }

    /**
     * 保存网址
     * @param website 网址信息
     * @return
     */
    @PostMapping("/saveWebsite")
    @ApiIdempotent
    public ResultJson saveWebsite(@Validated(AddGroup.class) Website website){
        String msg = checkWebsite(website);
        if (msg != null){
            return ResultJson.error(msg);
        }

        website.setId(IdTool.getId());
        website.setUserId(StpUtil.getLoginIdAsString());
        website.setNumberOfClicks(0);
        EntityTool.buildSaveBase(website, StpUtil.getLoginIdAsString());
        websiteService.save(website);
        return ResultJson.success(website);
    }

    /**
     * 获取网址类型
     * @return
     */
    @PostMapping("/getWebsiteType")
    public ResultJson<List<Dict>> getWebsiteType(){
        List<Dict> dictList = dictService.getType(Constant.RetainDictGroup.WEB_GROUP, StpUtil.getLoginIdAsString());
        return ResultJson.success(dictList);
    }

    /**
     * 检查和补充网址信息
     * @param website 网址信息
     * @return 非null则是错误信息
     */
    private String checkWebsite(Website website){
        Website websiteDb = websiteService.getWebsiteByUrl(website.getId(), StpUtil.getLoginIdAsString(), website.getUrl());
        if (websiteDb != null){
            return "该网址已收录，不需要重复录入";
        }
        if (!Validator.isUrl(website.getUrl())){
            return "网址非有效URL，需要带http或https";
        }

        // 数据进行补充
        if (website.getCommonlyUsed() == null){
            website.setCommonlyUsed(Constant.YesOrNo.NO);
        }
        return null;
    }


}
